<template>
	<view class="container flex-items-plus flex-column">
		<view class="login-logoBox">
			<image class="login-logo" src="/static/image/logo.png"></image>
		</view>
		<view class="loading-text">
			<text v-if="loading">正在登录中...</text>
			<text v-else-if="loginSuccess">登录成功，正在跳转...</text>
			<text v-else>登录失败，请重试</text>
		</view>
	</view>
</template>

<script setup>
import { inject, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import request from '@/utils/request.js';

const $store = inject('$store')
const loading = ref(true)
const loginSuccess = ref(false)

onLoad((options) => {
	// 获取URL中的code参数
	const code = getUrlParam('code');
	
	if (code) {
		// 调用后端微信登录接口
		wechatLogin(code);
	} else {
		loading.value = false;
		uni.showToast({
			title: '微信授权失败',
			icon: 'none'
		});
	}
})

// 获取URL参数
const getUrlParam = (name) => {
	const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
	const r = window.location.search.substr(1).match(reg);
	if (r != null) {
		return unescape(r[2]);
	}
	return null;
}

// 微信登录
const wechatLogin = (code) => {
	// 构造请求参数，适配后端接口
	const requestData = {
		code: code
	};
	
	request.post('auth/wechatPublicLogin', requestData).then(res => {
		loading.value = false;
		
		if (res.code == 0) {
			loginSuccess.value = true;
			uni.setStorageSync("token", res.result.token);
			uni.setStorageSync("userId", res.result.userId);
			getUserInfo()
		} else {
			uni.showToast({
				title: res.msg || '登录失败',
				icon: 'none'
			});
		}
	}).catch(err => {
		loading.value = false;
		uni.showToast({
			title: '登录失败，请重试',
			icon: 'none'
		});
		console.error('微信登录失败:', err);
	})
}

const getUserInfo = () => {
	request.get("user/userInfo").then(res => {
		let loginUser = res.result;
		$store.commit('setLoginUser', loginUser);
		if(loginUser == null || loginUser.userName == null){
			uni.reLaunch({
				url:"/pages/guide/step"
			})
		}else{
			uni.switchTab({
				url:"/pages/index/index"
			})
		}
	})
}
</script>

<style lang="scss" scoped>
.container {
	background-color: #FFFFFF;
	min-height: 100%;
	width: 100%;
	position: absolute;

	.login-logoBox {
		margin-top: -300rpx;

		.login-logo {
			width: 200rpx;
			height: 200rpx;
		}
	}
	
	.loading-text {
		margin-top: 50rpx;
		font-size: 32rpx;
		color: #666666;
	}
}

.flex-items-plus {
	display: flex;
	justify-content: center;
	align-items: center;
}

.flex-column {
	flex-direction: column
}
</style>